package chapter5;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author caiya
 * @date 2020/3/30 20:32
 */
public class SynchronousQueueTest {
    public static void main(String[] args) {
        /**
         * SynchronousQueue：同步队列，没有存储能力，put、take会直接阻塞
         */
        SynchronousQueue<Integer> queue = new SynchronousQueue<>();
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();
    }

    @Slf4j
    @AllArgsConstructor
    static class Producer implements Runnable {
        private SynchronousQueue<Integer> queue;

        @Override
        public void run() {
            while (true) {
                try {
                    int anInt = ThreadLocalRandom.current().nextInt(100000);
                    log.debug(Thread.currentThread().getName() + " put " + anInt);
                    queue.put(anInt);
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Slf4j
    @AllArgsConstructor
    static class Consumer implements Runnable {
        private SynchronousQueue<Integer> queue;

        @Override
        public void run() {
            while (true) {
                try {
                    Integer integer = queue.take();
                    log.debug(Thread.currentThread().getName() + " get " + integer);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
